package com.msg.test;

import com.msg.test.model.*;
import com.msg.test.util.MsgUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/10/19 0019.
 */
public class SocketService {
    private static Log log = LogFactory.getLog(SocketService.class);
    private List<byte[]> sendData = new ArrayList<byte[]>();
    private List<byte[]> getData = new ArrayList<byte[]>();
    private DataOutputStream out;
    private DataInputStream in;

    public SocketService(DataOutputStream out,DataInputStream in){
        super();
        this.out = out;
        this.in = in;
    }

    public void setDataList(List<byte[]> dataList){
        this.sendData = dataList;
    }

    public boolean start() throws Exception{
        boolean success = false;
        if (out != null && null != sendData){
            for (byte[] data : sendData){
                sendMsg(data);
                byte[] returnData = getInData();
                if (null != returnData){
                    getData.add(returnData);
                }
            }
        }
        if (in != null && null != getData){
            for (byte[] data : getData){
                    if (data.length >= 8){
                    MsgHead head = new MsgHead(data);
                    switch (head.getCommandId()){
                        case MsgCommand.CMPP_CONNECT_RESP:
                            MsgConnectResp connectResp = new MsgConnectResp(data);
                            if (connectResp.getStatus() == 0){
                                success = true;
                            }
                            log.info("CMPP_CONNECT_RESP,status:" + connectResp.getStatus() + ";序列号："+connectResp.getSequence());
                            break;
                        case MsgCommand.CMPP_ACTIVE_TEST_RESP:
                            MsgActiveTestResp activeTestResp = new MsgActiveTestResp(data);
                            log.info("短信网关与短信网关进行连接检查。序列号："+activeTestResp.getSequence());
                            break;
                        case MsgCommand.CMPP_SUBMIT_RESP:
                            MsgSubmitResp submitResp = new MsgSubmitResp(data);
                            if (submitResp.getResult() == 0){
                                success = true;
                            }
                            log.info("CMPP_SUBMIT_RESP,status:" + submitResp.getResult() + " 序列号：" + submitResp.getSequence());
                            break;
                        case MsgCommand.CMPP_TERMINATE_RESP:
                            log.info("拆除与IMSG的链接  序列号：" + head.getSequence());
                            break;
                        case MsgCommand.CMPP_CANCEL_RESP:
                            log.info("CMPP_CANCEL_RESP 序列号：" + head.getSequence());
                            break;
                        case MsgCommand.CMPP_CANCEL:
                            log.info("CMPP_CANCEL 序列号：" + head.getSequence());
                            break;
                        case MsgCommand.CMPP_DELIVER:
                            MsgDeliver msgDeliver = new MsgDeliver(data);
                            if (msgDeliver.getResult() == 0){
                                log.info("CMPP_DELIVER 序列号：" + head.getSequence() + ",是否消息回复" + (msgDeliver.getRegistered_Delivery() == 0 ?"不是，消息内容：" + msgDeliver.getsMSC_seqence():"是，目的手机号：" + msgDeliver.getDest_terminal_Id()));
                            }else{
                                log.info("CMPP_DELIVER 序列号：" + head.getSequence());
                            }
                            MsgDeliverResp msgDeliverResp = new MsgDeliverResp();
                            msgDeliverResp.setTotalLength(12+8+4);
                            msgDeliverResp.setCommandId(MsgCommand.CMPP_DELIVER_RESP);
                            msgDeliverResp.setSequence(MsgUtil.getSequence());
                            msgDeliverResp.setMsg_Id(msgDeliver.getMsg_Id());
                            msgDeliverResp.setResult(msgDeliver.getResult());
                            sendMsg(msgDeliverResp.toByteArray());
                            break;
                        case MsgCommand.CMPP_DELIVER_RESP:
                            log.info("CMPP_DELIVER_RESP 序列号："+head.getSequence());
                            break;
                        case MsgCommand.CMPP_QUERY:
                            log.info("CMPP_QUERY 序列号："+head.getSequence());
                            break;
                        case MsgCommand.CMPP_QUERY_RESP:
                            log.info("CMPP_QUERY_RESP 序列号："+head.getSequence());
                            break;
                        case MsgCommand.CMPP_TERMINATE:
                            log.info("CMPP_TERMINATE 序列号："+head.getSequence());
                            break;
                        case MsgCommand.CMPP_CONNECT:
                            log.info("CMPP_CONNECT 序列号："+head.getSequence());
                            break;
                        case MsgCommand.CMPP_ACTIVE_TEST:
                            log.info("CMPP_ACTIVE_TEST 序列号："+head.getSequence());
                            break;
                        case MsgCommand.CMPP_SUBMIT:
                            log.info("CMPP_SUBMIT 序列号："+head.getSequence());
                            break;
                        default:
                            log.error("无法解析IMSP返回的包结构：包长度为："+head.getTotalLength());
                            break;
                    }
                }
            }
        }
        return success;
    }

    private boolean sendMsg(byte[] data) throws IOException {
        try{
            out.write(data);
            out.flush();
            return true;
        }catch (NullPointerException ex){
            log.error("在此次发送已打包的消息字节：无字节输入");
        }
        return false;
    }

    private byte[] getInData() throws IOException {
        try {
            int length = in.readInt();
            if (null != in && 0 != length){
                byte[] data = new byte[length - 4];
                in.read(data);
                return data;
            }else{
                return null;
            }
        } catch (NullPointerException e) {
            log.error("在本链接上接受字节消息：无流输入");
            return null;
        } catch (EOFException efo){
            log.error("在本链接上接受字节消息："+efo.getMessage());
            return null;
        }

    }
}
